/**
 * 临时数据获取接口测试用例
 *
 * Created by liuxuechao on 2022/08/09.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const randomstring = require('randomstring');

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');

module.exports = describe('/GET ephemeral-data.json', function () {
  const url = '/ephemeral-data.json';
  const administrator = new Administrator();
  const newUserIds = [];
  let tester;
  let key;

  before(function (done) {
    administrator.createRandomTester()
      .then((user) => {
        tester = user;
        newUserIds.push(user.userId);
        return tester.storageEphemeralData();
      })
      .then((data) => {
        key = data.key;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => administrator.logout())
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.tester(uri, url, 'get');

  // 正常请求临时数据
  it('it should get ephemeral data', function (done) {
    tester.login()
      .then(() => {
        chai.request(uri)
          .get(url)
          .set('Authorization', `Bearer ${tester.token.accessToken}`)
          .query({ key })
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.ephemeralMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // key字段缺失
  it('it should fail to get data when lossing key field', function (done) {
    tester.login()
      .then(() => {
        chai.request(uri)
          .get(url)
          .set('Authorization', `Bearer ${tester.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(400);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // key无效
  it('it should get null data when key is invalid', function (done) {
    const invalidKey = randomstring.generate({ length: 24, charset: 'hex' });
    tester.login()
      .then(() => {
        chai.request(uri)
          .get(url)
          .set('Authorization', `Bearer ${tester.token.accessToken}`)
          .query({ key: invalidKey })
          .end((err, res) => {
            res.should.have.status(200);
            res.body.should.be.a('object');
            res.body.should.have.property('key');
            should.equal(res.body.key, null);
            res.body.should.have.property('data');
            should.equal(res.body.data, null);
            done();
          });
      })
      .catch(done);
  });
});
